<?php

namespace App\Exceptions;

use Exception;

class CommonException extends Exception {

    const HTTP_OK = 200;

    protected $data;
    protected $code;

    /**
     *   
     * @param string|array $data  内容
     * @param int $code 任意httpStatus（如200，201，204，301，422，500），就只返回httpStatus，如果是自定义错误编码，（如600101，600102），就返回httpstatus为200，返回体中包含message和code
     * @param array $meta 
     */
    public function __construct($data, int $code = self::HTTP_OK, array $meta = []) {
        $this->data = $data;
        $this->code = $code;
        $this->meta = $meta;
        // parent::__construct($data, $code);
    }

    public function report() {
        //
    }

    public function render() {
        $httpStatus = getHttpStatus();
        $status = in_array($this->code, $httpStatus) ? $this->code : self::HTTP_OK;
        $content = [];
        if (is_array($this->data)) {
            $content = $this->data;
        }
        if (is_string($this->data)) {
            $content = in_array($this->code, $httpStatus) ? [
                'message' => $this->data
                    ] : [
                'message' => $this->data,
                'code' => $this->code,
            ];
        }

        if ($this->meta) {
            $content = array_add($content, 'meta', $this->meta);
        }

        return response()->json($content, $status);
    }

}
